package com.yj.suncity.publish;

import java.util.ArrayList;

import com.yj.suncity.R;
import com.yj.suncity.constant.URLCon;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class SelectPicShowActivity extends Activity {
	private ArrayList<String> pathsAll;
	private int position;
	private TextView mTxtCurrentCount;
	private TextView mTxtAllCount;
	private ViewPager pager;
	private int currentPager = 0;
	private MyPagerAdapter pagerAdapter;

	private DisplayImageOptions options;
	private int posi;
	private boolean isSelectImg;
	private String head;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_select_pic_gallery);

		posi = getIntent().getExtras().getInt("posi", 0);
		isSelectImg = getIntent().getBooleanExtra("selectimg", true);
		pathsAll = getIntent().getExtras().getStringArrayList("paths");
		options = new DisplayImageOptions.Builder()
				.showImageForEmptyUri(R.drawable.android_layout_bg)
				.showImageOnFail(R.drawable.android_layout_bg)
				.resetViewBeforeLoading(true).cacheOnDisc(true)
				.imageScaleType(ImageScaleType.EXACTLY)
				.bitmapConfig(Bitmap.Config.RGB_565)
				.displayer(new FadeInBitmapDisplayer(300)).build();
		head = isSelectImg ? "file://" : URLCon.HOST;

		findView(pathsAll, posi);

	}

	private void findView(ArrayList<String> paths, int index) {
		mTxtCurrentCount = (TextView) findViewById(R.id.txt_current_count);
		mTxtAllCount = (TextView) findViewById(R.id.txt_all_count);

		mTxtCurrentCount.setText(String.valueOf(index + 1));// 当前张数
		mTxtAllCount.setText(String.valueOf(pathsAll.size()));// 显示gallery的总张数
		position = index;// 初始化当前选中下标
		pager = (ViewPager) findViewById(R.id.viewpage);

		pagerAdapter = new MyPagerAdapter();
		pager.setAdapter(pagerAdapter);
		pager.setCurrentItem(index);
		pager.setOnPageChangeListener(new MyPageChangeListener());
	}

	// viewPage
	public class MyPageChangeListener implements OnPageChangeListener {
		@Override
		public void onPageScrollStateChanged(int arg0) {
			// 点击是1，放开是0，滚动是2
			// Log.d(TAG, ""+arg0);

		}

		@Override
		public void onPageScrolled(int arg0, float arg1, int arg2) {
			// Log.d(TAG,"========arg0====="+ arg0);
			// Log.d(TAG,"======arg1======"+ arg1);
			// Log.d(TAG,"========arg2====="+ arg2);
		}

		// 当前页
		@Override
		public void onPageSelected(int arg0) {
			currentPager = arg0;
			SelectPicShowActivity.this.position = currentPager;
			mTxtCurrentCount.setText(String.valueOf(position + 1));// 当滑动gallery时显示当前是第几张
			// Log.d(TAG,"---------arg2----"+ arg0);
		}
	}

	class MyPagerAdapter extends PagerAdapter {

		private LayoutInflater inflater;
		private ImageLoader imageLoader;

		MyPagerAdapter() {
			imageLoader = ImageLoader.getInstance();
			inflater = getLayoutInflater();
		}

		@Override
		public int getItemPosition(Object object) {
			// TODO Auto-generated method stub
			return POSITION_NONE;
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return pathsAll.size();
		}

		@Override
		public void destroyItem(ViewGroup container, int position, Object object) {
			((ViewPager) container).removeView((View) object);
			// super.destroyItem(container, position, object);
		}

		@Override
		public Object instantiateItem(ViewGroup view, int position) {
			View imageLayout = inflater.inflate(R.layout.item_pager_image,
					view, false);
			ImageView imageView = (ImageView) imageLayout
					.findViewById(R.id.image);
			final ProgressBar spinner = (ProgressBar) imageLayout
					.findViewById(R.id.loading);

			imageLoader.displayImage(head + pathsAll.get(position), imageView,
					options, new SimpleImageLoadingListener() {
						@Override
						public void onLoadingStarted(String imageUri, View view) {
							spinner.setVisibility(View.VISIBLE);
						}

						@Override
						public void onLoadingFailed(String imageUri, View view,
								FailReason failReason) {
							String message = null;
							switch (failReason.getType()) { // 获取图片失败类型
							case IO_ERROR: // 文件I/O错误
								message = "Input/Output error";
								break;
							case DECODING_ERROR: // 解码错误
								message = "Image can't be decoded";
								break;
							case NETWORK_DENIED: // 网络延迟
								message = "Downloads are denied";
								break;
							case OUT_OF_MEMORY: // 内存不足
								message = "Out Of Memory error";
								break;
							case UNKNOWN: // 原因不明
								message = "Unknown error";
								break;
							}
							Toast.makeText(SelectPicShowActivity.this, message,
									Toast.LENGTH_SHORT).show();

							spinner.setVisibility(View.GONE);
						}

						@Override
						public void onLoadingComplete(String imageUri,
								View view, Bitmap loadedImage) {
							spinner.setVisibility(View.GONE); // 不显示圆形进度条
						}
					});
			((ViewPager) view).addView(imageLayout, 0); // 将图片增加到ViewPager
			return imageLayout;
		}

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			return arg0 == arg1;
		}
	}

	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btnHeadBack:
			Intent intent = new Intent();
			Bundle bundle = new Bundle();
			bundle.putStringArrayList("picPaths", pathsAll);
			intent.putExtras(bundle);
			intent.putExtra("selectimg", isSelectImg);
			setResult(103, intent);
			this.finish();
			break;
		case R.id.del_select_pic:
			if (pathsAll.size() <= 0) {
				return;
			}
			pathsAll.remove(position);
			mTxtAllCount.setText(String.valueOf(pathsAll.size()));
			if (pathsAll.size() == 0) {
				Intent intent1 = new Intent();
				intent1.putExtra("selectimg", isSelectImg);
				setResult(104,intent1);
				SelectPicShowActivity.this.finish();
			}

			// 当点击的是最后一张图片时，将下标减去1，否则会下标溢出异常
			if (position == pathsAll.size()) {
				position = position - 1;
			}
			pagerAdapter.notifyDataSetChanged();
			break;
		default:
			break;
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			Intent intent = new Intent();
			Bundle bundle = new Bundle();
			bundle.putStringArrayList("picPaths", pathsAll);
			intent.putExtras(bundle);
			intent.putExtra("selectimg", isSelectImg);
			setResult(103, intent);
		}
		return super.onKeyDown(keyCode, event);
	}

}
